package com.decheng.common;

import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author 孔德成
 * @Slogan 致敬大师，致敬未来的你
 */
public class MyTemplateEngine extends TemplateEngine {

    private static final MyTemplateEngine INSTANCE = new MyTemplateEngine();

    private static ServletContextTemplateResolver templateResolver;

    private MyTemplateEngine() {
    }

    public static MyTemplateEngine getInstance(ServletContext servletContext) {

        // 如果视图解析器没有初始化，则配置视图解析器
        if (templateResolver == null) {
            // 1.创建Thymeleaf解析器对象
            templateResolver = new ServletContextTemplateResolver(servletContext);
            templateResolver.setTemplateMode(TemplateMode.HTML);
            String viewPrefix = servletContext.getInitParameter("view-prefix");
            templateResolver.setPrefix(viewPrefix);
            String viewSuffix = servletContext.getInitParameter("view-suffix");
            templateResolver.setSuffix(viewSuffix);
            templateResolver.setCacheTTLMs(60000L);
            templateResolver.setCacheable(true);
            templateResolver.setCharacterEncoding("utf-8");
            // 2.给模板引擎对象设置模板解析器
            INSTANCE.setTemplateResolver(templateResolver);
        }
        return INSTANCE;
    }

    public void processTemplate(String templateName, HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 1.设置响应体内容类型和字符集
        resp.setContentType("text/html;charset=UTF-8");

        // 2.创建WebContext对象
        WebContext webContext = new WebContext(req, resp, req.getServletContext());

        // 3.处理模板数据
        INSTANCE.process(templateName, webContext, resp.getWriter());
    }
}
